﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Data;
using HtmlAgilityPack;

namespace Extractor.LibCode
{
    public struct SCORESWAY_MATCH
    {
        // http://www.scoresway.com/b/block.competition_matches?gameweek=9&round_id=17950&season_id=7185&competition_id=8
        //&stamp=1352709900&sport=soccer&localization_id=www        
        public string gameweek { get; set; }
        public string roundid { get; set; }
        public string sessionid { get; set; }
        public string competitionid { get; set; }
        public string stamp { get; set; }
    }

    public class cMatch : cDBService
    {
        #region Properties

        //scoresway property
        private SCORESWAY_MATCH sw_match;

        private string competitionid;

        public string Competitionid
        {
            get { return competitionid; }
            set { competitionid = value; }
        }
        private string sessionid;

        public string Sessionid
        {
            get { return sessionid; }
            set { sessionid = value; }
        }
        private string roundtype;

        public string Roundtype
        {
            get { return roundtype; }
            set { roundtype = value; }
        }
        private int istage;

        public int Intstage
        {
            get { return istage; }
            set { istage = value; }
        }
        private string groupmatch;

        public string Groupmatch
        {
            get { return groupmatch; }
            set { groupmatch = value; }
        }

        private string pagehtml;


        private const string table_name_hdr = "TBCOMPMATCH";
        private const string table_name_det = "TBCOMPMATCHDET";

        private cMapping oMapping;


        private string yuerel = "http://www.scoresway.com/b/block.competition_matches?gameweek=9&round_id=17950&season_id=7185&competition_id=8&stamp=1352709900&sport=soccer&localization_id=www";

        public DataTable dtMatch;
        #endregion

        public cMatch()
        {
            oMapping = new cMapping();

        }

        public cMatch(string surl)
        {
            oMapping = new cMapping();
            ExtractMatch(surl);

        }


        
        // http://www.scoresway.com/b/block.competition_matches?gameweek=9&round_id=17950&season_id=7185&competition_id=8&stamp=1352709900&sport=soccer&localization_id=www
        public void ExtractMatch(string matchurl)
        {
            dtMatch = new DataTable();
          dtMatch=  cCommon.initTable(new string[] { "MatchID", "tanggal", "teamA_ID", "teamA_name", "scoretime", "teamB_ID", "teamB_name" });
            ExtractMatch(ref dtMatch, matchurl);

        }
        public DataTable ExtractMatch(ref DataTable dt ,string url)
        {
           // return new DataTable();
            Uri myUri = new Uri(url);
            if (myUri == null)
                new Exception(this.GetType() + " - ExtractMatch:" + "Invalid Addres");

            sw_match.competitionid = HttpUtility.ParseQueryString(myUri.Query).Get("competition_id");
            sw_match.gameweek = HttpUtility.ParseQueryString(myUri.Query).Get("gameweek");
            sw_match.sessionid = HttpUtility.ParseQueryString(myUri.Query).Get("season_id");
            sw_match.stamp = HttpUtility.ParseQueryString(myUri.Query).Get("stamp");
            sw_match.roundid = HttpUtility.ParseQueryString(myUri.Query).Get("round_id");


            Competitionid = oMapping.getLocalCode(cMapping.MAPPING_TYPE.COMPETITIONID, SITE_MAPPING.SCORESWAY, sw_match.competitionid);
            Sessionid = oMapping.getLocalCode(cMapping.MAPPING_TYPE.SESSIONID, SITE_MAPPING.SCORESWAY, sw_match.sessionid);
            Roundtype = oMapping.getLocalCode(cMapping.MAPPING_TYPE.ROUNDID, SITE_MAPPING.SCORESWAY, sw_match.roundid);
            int.TryParse(sw_match.gameweek, out istage);




            WebClient client = new WebClient();
            pagehtml = client.DownloadString(myUri);
            //client.DownloadStringAsync(myUri);
            //pagehtml = cCommon.strimLine(System.IO.File.ReadAllLines(Properties.Settings.Default.pathdata+"\\match.txt"));
            DataRow dr = dt.NewRow();
            if (pagehtml != null)
            {
                HtmlDocument doc = new HtmlDocument();

                doc.Load(new StringReader(pagehtml));
                foreach (HtmlNode hn in doc.DocumentNode.SelectNodes("//td"))
                {
                    if(hn.Attributes["class"]!=null)
                    {
                        HtmlNode hn2;
                        if(hn.Attributes["class"].Value=="date no-repetition")
                        {
                            dr = dt.NewRow();
                             hn2 = hn.SelectSingleNode("//span[@data-format='dd/mm/yy']");                            
                                dr["tanggal"] = hn2.InnerText;   
                        }

                        if (hn.Attributes["class"].Value == "team team-a " || hn.Attributes["class"].Value == "team team-a strong")
                        {
                           // HtmlDocument hdc = new HtmlDocument();
                           // hdc.Load(new StringReader(hn.InnerHtml));
                           //hn2= hn.SelectSingleNode("//a");
                            hn2 = hn.SelectSingleNode("a");
                           
                             dr["teamA_ID"] = hn2.Attributes["href"].Value.Replace("?sport=soccer&page=team&id=", "");
                             dr["teamA_name"] = hn2.Attributes["title"].Value;

                        }

                        if (hn.Attributes["class"].Value == "score-time score")
                        {
                            hn2 = hn.SelectSingleNode("a/span");                           
                            dr["scoretime"] = hn2.InnerText;

                            hn2 = hn.SelectSingleNode("a");
                            dr["MatchID"] = hn2.Attributes["href"].Value.Replace("?sport=soccer&page=match&id=", "");
                        }

                        if (hn.Attributes["class"].Value == "score-time status")
                        {
                            hn2 = hn.SelectSingleNode("a/span");
                            if (hn2 != null)
                            {
                                dr["scoretime"] = hn2.InnerText;
                            }
                            else
                            {
                                hn2 = hn.SelectSingleNode("a");
                                dr["scoretime"] = hn2.InnerText.Trim();
                            }

                            hn2 = hn.SelectSingleNode("a");
                            dr["MatchID"] = hn2.Attributes["href"].Value.Replace("?sport=soccer&page=match&id=", "");
                        }

                        if (hn.Attributes["class"].Value == "team team-b " || hn.Attributes["class"].Value == "team team-b strong")
                        {
                            hn2 = hn.SelectSingleNode("a");
                            dr["teamB_ID"] = hn2.Attributes["href"].Value.Replace("?sport=soccer&page=team&id=", "");
                            dr["teamB_name"] = hn2.Attributes["title"].Value;

                        }

                        if (hn.Attributes["class"].Value == "info-button button")
                        {
                            dt.Rows.Add(dr);
                        }

                         //"MatchID","tanggal", "teamA_ID", "teamA_name", "scoretime", "teamB_ID", "teamB_name" 
                    }

                }



            }


            return dt;
        }

        public string getCompMatch(string compid,string sessid,string sround, int istage,string sgroup)
        {
            string sql=string.Format(@"select COMPMATCHID from TBCOMPMATCH where COMPETITIONID='{0}' 
                                        and SESSIONID='{1}' and ROUNDID='{2}' and STAGEMATCH={3}",
                                        compid,sessid,sround,istage);


            if(sgroup!=null)
                sql+=" and GROUPMATCH='"+sgroup+"'";

            string sid = Dbserver.ExecuteScalar(sql).ToString();
            if (sid.Trim() == string.Empty)
            {
                sid = new cDBHelper().genIDCommit("COMPMATCH");
                return sid;
            }
            else
            {
                return sid;
            }                
        }

        int sqlupddate(DataTable dt,string dtname)
        {
            int nret = 0;
            if (Dbserver.openConn())
            {
                string s="";
                
                nret=Dbserver.SqlUpdate(dt, dtname, out s);
                Dbserver.CommitAndCloseConn();               

            }
            return nret;

        }
        DateTime getTanggal(String s)
        {
            DateTime d = DateTime.Parse("1900-01-01");
            //18/8/12

            string[] ss = s.Split('/');
            if (ss.Length == 3)
                DateTime.TryParse("20" + ss[2] + "/" + ss[1] + "/" + ss[0], out d);
            return d;
        }
        public bool Save()
        {
          
            DataTable dtsavedet = getTableStructure(table_name_det);          

            foreach(DataRow drr in dtMatch.Rows)
            {
                
                DataTable dtsavehdr = getTableStructure(table_name_hdr);
                DataRow dr = dtsavehdr.NewRow();

                DataRow drdet = dtsavedet.NewRow();

                string matchid= drr["MatchID"].ToString();
                if(matchid.Trim()==string.Empty)
                throw new Exception("cMatch - SAVE : Invalid Match ID or Match ID Not Found");
                string localcode=oMapping.getLocalCodeAndCreate(cMapping.MAPPING_TYPE.MATCHID,SITE_MAPPING.SCORESWAY,matchid);
                dr["COMPMATCHID"] = getCompMatch(Competitionid, Sessionid, Roundtype, Intstage, Groupmatch); //localcode;
                //localcode=oMapping.getLocalCodeAndCreate(cMapping.MAPPING_TYPE.MATCHID,cMapping.SITE_MAPPING.SCORESWAY,matchid);
                dr["COMPETITIONID"] = Competitionid; //oMapping.getLocalCodeAndCreate(cMapping.MAPPING_TYPE.MATCHID, cMapping.SITE_MAPPING.SCORESWAY, sw_match.competitionid);
                dr["SESSIONID"] = Sessionid;
                dr["ROUNDID"] = Roundtype;
                dr["STAGEMATCH"] = this.Intstage;
                if (groupmatch!= null)
                {
                    dr["GROUPMATCH"] = groupmatch;
                }
                dtsavehdr.Rows.Add(dr);
                //MATCHID","COMPMATCHID","HOMETEAMID","AWAYTEAMID","KICKOFDATE","KICKOFTIME","VENUEID","FINALSCORE",
                //"HALFTIME","FULLTIME","EXTRATIME","PINALTIES","ATTENDANCE","REFEREE","ASSISTANTS1","ASSISTANTS2",
                //"FOURTHOFFICIAL","DTCREATED","DTUPDATED

                //detail
                
                drdet["MATCHID"] = localcode;
                drdet["COMPMATCHID"] = dr["COMPMATCHID"].ToString();
               // cTeam oteam= new cTeam(drr["teamA_ID"].ToString(),localcode);
                //localcode=oMapping.get
                drdet["HOMETEAMID"] = new cTeam().checkncreateTeam( drr["teamA_ID"].ToString(),drr["teamA_name"].ToString(),SITE_MAPPING.SCORESWAY);

                drdet["AWAYTEAMID"] = new cTeam().checkncreateTeam(drr["teamB_ID"].ToString(), drr["teamB_name"].ToString(), SITE_MAPPING.SCORESWAY); 
                drdet["KICKOFDATE"] = getTanggal(drr["tanggal"].ToString());
                //drdet["KICKOFTIME"] = drr["teamB_ID"]; ;
                //drdet["VENUEID"] = drr["teamB_ID"]; ;
                drdet["FINALSCORE"] = drr["scoretime"]; ;
                //drdet["HALFTIME"] = drr["teamB_ID"];
                //drdet["FULLTIME"] = drr["teamB_ID"]; ;
                //drdet["EXTRATIME"] = drr["teamB_ID"]; ;
                //drdet["PINALTIES"] = drr["teamB_ID"]; ;
                //drdet["ATTENDANCE"] = drr["teamB_ID"]; ;
                //drdet["REFEREE"] = drr["teamB_ID"]; ;
                //drdet["ASSISTANTS1"] = drr["teamB_ID"]; ;
                //drdet["ASSISTANTS2"] = drr["teamB_ID"]; ;
                //drdet["FOURTHOFFICIAL"] = drr["teamB_ID"]; ;
                // drdet["ASSISTANTS1"] = drr["teamB_ID"]; ;
                dtsavedet.Rows.Add(drdet);


                //"MatchID", "tanggal", "teamA_ID", "teamA_name", "scoretime", "teamB_ID", "teamB_name" });
                //RECID" "COMPMATCHID" "COMPETITIONID" "SESSIONID" "ROUNDID" "STAGEMATCH" "GROUPMATCH

                sqlupddate(dtsavehdr, table_name_hdr);
               
            }

            sqlupddate(dtsavedet, table_name_det);

            return true;
            

        }
        

    }
}
